<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input
            placeholder="用户名"
            v-model="searchModel.username"
            clearable
          >
          </el-input>
          <el-select
            v-model="searchModel.statusId"
            placeholder="用户状态"
            clearable
          >
            <el-option label="正常" value="1"></el-option>
            <el-option label="冻结" value="2"></el-option>
          </el-select>
          <el-button
            @click="getUserList"
            type="primary"
            round
            icon="el-icon-search"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4" align="right">
          <el-button
            @click="openEditUi(null)"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="userList" style="width: 100%">
        <el-table-column label="序号">
          <template slot-scope="scope">
            <!-- 作用域插槽 -->
            <!-- (pageNum-1)*pageSize + index +1 -->
            {{
              (searchModel.pageNum - 1) * searchModel.pageSize +
              scope.$index +
              1
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="id" label="用户ID" width="180">
        </el-table-column> -->
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="createdAt" label="创建时间"> </el-table-column>
        <el-table-column prop="statusId" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.statusId == 1">正常</el-tag>
            <el-tag v-else type="danger">冻结</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="电子邮箱"> </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="primary" icon="el-icon-edit" circle></el-button> -->
            <el-button
              round
              type="primary"
              size="mini"
              @click="openEditUi(scope.row.id)"
              >编辑</el-button
            >
            <!-- <el-button type="danger" icon="el-icon-delete" circle></el-button> -->
            <el-button
              type="success"
              round
              size="mini"
              v-if="scope.row.statusId == 2"
              @click="unfreezeUser(scope.row)"
              >解冻</el-button
            >
            <el-button
              type="warning"
              round
              size="mini"
              v-if="scope.row.statusId == 1"
              @click="freezeUser(scope.row)"
              >冻结</el-button
            >
            <el-button
              type="danger"
              round
              size="mini"
              @click="deleteUser(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNum"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 用户编辑对话框 -->
    <el-dialog
      @close="clearForm"
      :title="title"
      :visible.sync="dialogFormVisible"
      width="40%"
    >
      <el-form :model="userForm" :rules="rules" ref="userFormRef">
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="userForm.password"
            autocomplete="off"
            show-password
          ></el-input>
        </el-form-item>
        <!-- <el-form-item
          label="状态"
          :label-width="formLabelWidth"
          v-if="userForm.id != null || userForm.id != undefined"
        >
          <el-switch
            v-model="userForm.statusId"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item> -->
        <!-- <el-form-item
          label="电子邮箱"
          :label-width="formLabelWidth"
          prop="email"
        >
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/userManage";
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg =
        /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (!reg.test(value)) {
        return callback(new Error("邮箱格式不正确"));
      }
      callback();
    };
    return {
      message: "",
      formLabelWidth: "130px",
      userForm: {},
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNum: 1,
        pageSize: 10,
      },
      userList: [],
      delete: {
        id: 0,
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入电子邮件", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    unfreezeUser(user) {
      this.$confirm(`您确认解冻用户${user.username}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          userApi.unfreezeUser(user.id).then((response) => {
            if (response.success !== false) {
              this.$message({
                type: "success",
                message: "解冻成功!",
              });
              this.searchModel.pageNum = 1;
              this.getUserList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消解冻",
          });
        });
    },
    freezeUser(user) {
      this.$confirm(`您确认冻结用户${user.username}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          userApi.freezeUser(user.id).then((response) => {
            if (response.success !== false) {
              this.$message({
                type: "success",
                message: "冻结成功!",
              });
              this.searchModel.pageNum = 1;
              this.getUserList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消冻结",
          });
        });
    },
    deleteUser(user) {
      this.$confirm(`您确认删除用户${user.username}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delete.id = user.id;
          userApi.deleteUserById(this.delete).then((response) => {
            if (response.success !== false) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.searchModel.pageNum = 1;
              this.getUserList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    saveUser() {
      //提交时表单验证
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          //验证通过提交后台
          userApi.saveUser(this.userForm).then((response) => {
            //成功提示

            if (response.success !== false0) {
              this.$message({
                showClose: true,
                message: this.message,
                type: "success",
              });

              // 关闭对话框
              this.dialogFormVisible = false;

              //刷新表格
              this.getUserList();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearForm() {
      // 关闭表单时清空所有
      this.userForm = {};
      this.$refs.userFormRef.clearValidate();
    },
    openEditUi(id) {
      if (id === null) {
        this.title = "新增用户";
        this.message = "新增用户成功";
      } else {
        this.title = "修改用户";
        this.message = "修改用户成功";
        //根据id
        this.userForm = this.userList.find((user) => user.id === id);
        // console.log(this.userForm);
        this.userForm.userId = id;
        // console.log(this.userForm);
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.getUserList();
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.getUserList();
    },
    getUserList() {
      userApi.getUserList(this.searchModel).then((response) => {
        this.userList = response.records
          .filter((user) => user.id !== 1)
          .map((user) => {
            // 创建一个新的Date对象
            const date = new Date(user.createdAt);
            // 使用toISOString方法并截取日期部分来格式化日期
            const formattedDate = date.toISOString().split("T")[0];
            // 将格式化后的日期赋值给user对象的createdAt属性
            user.createdAt = formattedDate;
            // 返回更新后的user对象
            return user;
          });

        this.total = response.total;
        // console.log(response);
      });
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 15px;
}
.el-dialog .el-input {
  width: 85%;
}
.el-pagination {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
</style>
